package com.arvts.android.project;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.arvts.android.project.adapter.ConnectionDetector;
import com.arvts.android.project.adapter.SharedPreferencesClass;
import com.arvts.android.project.adapter.VehicleDetailsAdapter;
import com.arvts.android.project.data.VehicleDS;
import com.arvts.android.project.model.CurrentStatus;
import com.arvts.android.project.model.Vehicle;

public class ListOfVehicleNo extends Activity {

	
	public static final String SETTINGS = "SETTINGS";
	SharedPreferences localSP;
	
	ProgressDialog dialog;
	int TIMEOUT_MILLISEC = 10000;
	EditText t1, t2,areaCode,etEmail;
	String s = "";
	JSONObject jObject;
	
	public CurrentStatus status;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.vehicle_list_layout);
		
		localSP = getSharedPreferences(SETTINGS,Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
		
		status=new CurrentStatus();
		
		ListView list = (ListView) findViewById(R.id.listView1);

		VehicleDS vehicleDS = new VehicleDS(ListOfVehicleNo.this);
		list.clearTextFilter();

		final ArrayList<Vehicle> arrayList = vehicleDS.getAllVehicleDetails();
		list.setAdapter(new VehicleDetailsAdapter(ListOfVehicleNo.this,	arrayList));

		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Vehicle vehicle = arrayList.get(position);
				boolean connectionStatus = new ConnectionDetector(getApplicationContext()).isConnectingToInternet();
				
				if(connectionStatus == true){
					new get_map_data().execute(vehicle.getVEHICLE_ID());
				}else{
					Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();	
				}
			}
		});
	}

	
	
	
	
	
	class get_map_data extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(ListOfVehicleNo.this);
			dialog.setMessage("Please wait loading...");
			dialog.setIndeterminate(false);
			dialog.setCancelable(false);
			dialog.show();
		}

		protected String  doInBackground(String... args) {
		
			try{
				
			JSONObject json = new JSONObject();
				
				json.put("VEHICLE_ID", args[0]);
				
				HttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_MILLISEC);
				HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
				HttpClient httpclient = new DefaultHttpClient(httpParams);

				String url = Login.IP + "get_map_data.php";

				HttpPost request = new HttpPost(url);

				request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
				request.setHeader("json", json.toString());

				ResponseHandler<String> responseHandler = new BasicResponseHandler();

				String responseBody = httpclient.execute(request,responseHandler);

				// Parse
				JSONObject json1 = new JSONObject(responseBody);
				JSONArray jArray = json1.getJSONArray("posts");

				for (int i = 0; i < jArray.length(); i++) {

					JSONObject e = jArray.getJSONObject(i);
					s = e.getString("post");
					jObject = new JSONObject(s);

					Log.v("JsonString", s.toString());
					
					//Log.v("Start/Stop date 2", getDate(Long.parseLong(jObject.getString("TIME"))));
					
					String sLocation=jObject.getString("location");
					
					
					String[] tokens = sLocation.split(":");
					
					if(tokens[0].toUpperCase().toString().equals("GSM")){ //GSM:502:12:4188:20441:0.00000:0.00000:0:0
						
						String cellidUrl=Login.IP+"locate.php?mcc="+tokens[1].toString()+"&mnc="+tokens[2].toString()+"&lac="+tokens[3].toString()+"&cid="+tokens[4].toString();
						
						DefaultHttpClient httpclient1 = new DefaultHttpClient();
				        HttpGet httpget = new HttpGet(cellidUrl);
				        HttpResponse response = httpclient1.execute(httpget);
				        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				        StringBuffer sb = new StringBuffer("");
				        String line = "";
				        String NL = System.getProperty("line.separator");
				        
				        while ((line = in.readLine()) != null) {                    
				            sb.append(line + NL);
				        }
				        
				        in.close();
				        String result = sb.toString();
				       
				        Log.v("My Response :: ", result);
				        
				        String[] loc = result.split(":");
						
				        if(!result.equals("NOT_FOUND")){
							//SharedPreferencesClass.setLocalSharedPreference(getApplicationContext(), "latitude",loc[0]);
							//SharedPreferencesClass.setLocalSharedPreference(getApplicationContext(), "longitude",loc[1]);
				        	status.setVehicle_id(args[0]);
				        	status.setEcu_speed(jObject.getString("ecu_speed"));
							status.setStoped_or_started_time(getDate(Long.parseLong(jObject.getString("stoped_or_started_time"))));
							status.setGps_speed(jObject.getString("gps_speed"));
							status.setDate_and_time(getDate(Long.parseLong(jObject.getString("date_and_time"))));
							status.setStatus(jObject.getString("STATUS"));
							status.setTIME(getDate(Long.parseLong(jObject.getString("TIME"))));
							status.setLatitude(loc[0].toString());
							status.setLongitude(loc[1].toString());
							
							return "true";
							
						}else{
							return "false";
						}
					}else if(tokens[0].toUpperCase().toString().equals("GPS")){//GPS:5.41392:100.41111
			        	
						status.setVehicle_id(args[0]);
			        	status.setEcu_speed(jObject.getString("ecu_speed"));
						status.setStoped_or_started_time(getDate(Long.parseLong(jObject.getString("stoped_or_started_time"))));
						status.setGps_speed(jObject.getString("gps_speed"));
						status.setDate_and_time(getDate(Long.parseLong(jObject.getString("date_and_time"))));
						status.setStatus(jObject.getString("STATUS"));
						status.setTIME(getDate(Long.parseLong(jObject.getString("TIME"))));
						status.setLatitude(tokens[1].toString());
						status.setLongitude(tokens[2].toString());
										
					}

				}
			
			} catch (Exception e) {
				e.printStackTrace();
				return "false";
			}
			return "true";
			
		}

		protected void onPostExecute(final String stat) {

			dialog.dismiss();

			runOnUiThread(new Runnable() {
				public void run() {
					
				boolean connectionStatus = new ConnectionDetector(getApplicationContext()).isConnectingToInternet();
				
				if(connectionStatus == true){
					
					if(stat.equals("true")){	
						
						if(!(status.getLongitude().equals("")) && !(status.getLatitude().equals(""))){
							
							DashBoardActivity.status=status;
							Intent mainActivity = new Intent(ListOfVehicleNo.this,DashBoardActivity.class);
							startActivity(mainActivity);
							
						}else{
							Toast.makeText(ListOfVehicleNo.this, "connection Failed.",Toast.LENGTH_LONG).show();
						}
					}
					
					}else{
						Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();	
					}
				}
			});

		}

	}
	
	
	private String getDate(long time) {
	    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
	    cal.setTimeInMillis(time*1000);
	    String date = DateFormat.format("yyyy-MM-dd hh:mm:ss", cal).toString();
	    
	    return date;
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
	}

}
